package com.y4oung.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;
import com.y4oung.model.Business;
import com.y4oung.model.BusinessNew;
import com.y4oung.model.User;
import com.y4oung.service.IBusinessService;
import com.y4oung.service.IUserService;
import com.y4oung.util.ResponseJsonUtils;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;
    @Resource
    private IBusinessService businessService;
    
    @RequestMapping("/register.do")
    public void register(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String phone = request.getParameter("u_phone");
        String userName = "xiang";//request.getParameter("u_name");
        String userPassword = request.getParameter("u_pwd");
        boolean flag = this.userService.register(phone,userName,userPassword);
        JSONObject json = new JSONObject();
        json.put("result", flag);
        ResponseJsonUtils.json(response, json);
    }
    
    @RequestMapping("/login.do")
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String phone = request.getParameter("u_phone");
        String pwd = request.getParameter("u_pwd");
        User user = this.userService.login(phone);   
        JSONObject json = new JSONObject();
        if(user!=null&&pwd.equals(user.getPassword())){
        	HttpSession session = request.getSession();
        	session.setAttribute("user", user);
        	json.put("result", true);
        }else{
        	json.put("result", false);
        }
        ResponseJsonUtils.json(response, json);
//        ObjectMapper mapper = new ObjectMapper();
//        response.getWriter().write(mapper.writeValueAsString(user.getName()+"  "+user.getPassword()));
//        response.getWriter().close();
    }

    @RequestMapping("/showUser.do")
    public String showUserInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        User user =  (User)request.getSession().getAttribute("user");
//        ObjectMapper mapper = new ObjectMapper();
//        for (User user : userList) {
//        	response.getWriter().write(mapper.writeValueAsString(user));
//        }
//        response.getWriter().close();
        //User u = userService.getUserInfo(user.getId());
        request.setAttribute("user", user);
        return "information";
    }

    @RequestMapping("/showGallery.do")
    public String showGallery(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        List<Business> businessList;
        businessList = this.businessService.showBusinessList();
        String key = "businessList";
        request.setAttribute(key,businessList);
        
        return "restaurantsGallery";
    }


    @RequestMapping("/showsSearchGallery.do")
    public String showsSearchGallery(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        List<Business> businessList;
        businessList = this.businessService.showBusinessList();
        String key = "businessList";
        request.setAttribute(key,businessList);

        return "restaurantsGallery";
    }

    @ResponseBody
    @RequestMapping(value="/showBus.do",produces="text/plain;charset=utf-8")
    public String showBusiness(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        List<Business> businessList;
        businessList = this.businessService.showBusinessList();
        String busListStr = JSON.toJSONString(businessList);
        //JSONArray array = JSONArray.parseArray(busListStr);
        return busListStr;
}
    @RequestMapping("updateInfo")
    public void updateInfo(HttpServletRequest request, HttpServletResponse response){
    	String u_name = request.getParameter("u_name");
    	String u_email = request.getParameter("u_email");
    	String u_pwd = request.getParameter("u_pwd");
    	String u_phone = request.getParameter("u_phone");
    	String u_msg = request.getParameter("u_msg");
    	
    	User u =(User) request.getSession().getAttribute("user");
    	u.setName(u_name);
    	u.setEmail(u_email);
    	u.setPhone(u_phone);
    	u.setPassword(u_pwd);
    	boolean flag = true;
    	try {
            userService.updateUser(u.getId(), u.getName(), u.getIcon(), u.getPhone(), u.getEmail(), u.getPassword(), u.getMessage(), u.getCity());
        }catch (Exception e){
    	    flag = false;
        }
    	ResponseJsonUtils.json(response, flag);
    }

    @RequestMapping("/showResInfo.do")
    public String showInfo(HttpServletRequest request, HttpServletResponse response){
    	String r_id = request.getParameter("r_id");
    	//TODO  得到某个餐厅的信息
        Business business = businessService.showBusiness(Integer.valueOf(r_id));
        request.setAttribute("business", business);
    	System.out.println(r_id);
        return "restaurantInfo_new";
    }

    @RequestMapping("/showReview.do")
    public String showReview(){
        return "reviews";
    }

    @RequestMapping("/showContact.do")
    public String showContact(){
        return "contact";
    }

    @RequestMapping(value = "home", method = RequestMethod.GET)
    public String home(HttpServletRequest request, HttpServletResponse response){

        Map<String, Object> map = new HashMap<String, Object>();

        map.put("columns", "name");
        map.put("order", "DESC");

        List<Business> businessList = this.businessService.orderByColumns(map);
        request.setAttribute("recom_list",businessList);

        return "index";
    }

    @RequestMapping("/toLogin.do")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/toRegister.do")
    public String toRegister(){
        return "register";
    }

    @RequestMapping("/logout.do")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        request.getSession().removeAttribute("user");
        return "index";
    }


    @RequestMapping(value = "/fileRecieve", method = RequestMethod.POST)
	public ResponseEntity<JSONObject> recieveFile(HttpServletRequest request, HttpServletResponse response) {
		// 得到上传文件的保存目录，将上传的文件存放于WEB-INF目录下，不允许外界直接访问，保证上传文件的安全

		String savePath = request.getServletContext().getInitParameter("uploadFilePath");
		User u = (User) request.getSession().getAttribute("user");
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
		final MultipartFile photo = multipartRequest.getFile("files[]");
		final String fileName = photo.getOriginalFilename();
		savePath+="\\";
		savePath+=u.getId();
		File dir = new File(savePath);
		// 判断上传文件的保存目录是否存在


		if (!dir.exists() && !dir.isDirectory()) {
			System.out.println(savePath + "目录不存在，需要创建");
			// 创建目录

			dir.mkdir();
		}
		try {
			File file = new File(savePath, fileName);
			photo.transferTo(file);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		JSONObject json = new JSONObject();
		json.put("result", true);
		json.put("url", "user_img/" + fileName);
		
		u.setIcon("../user_img/" +u.getId()+"/"+ fileName);
		request.getSession().removeAttribute("user");
        userService.updateUser(u.getId(), u.getName(), u.getIcon(), u.getPhone(), u.getEmail(), u.getPassword(), u.getMessage(), u.getCity());
		request.getSession().setAttribute("user", u);
		HttpHeaders responseHeaders = new HttpHeaders();
		MediaType mediaType = new MediaType("text", "html", Charset.forName("UTF-8"));
		responseHeaders.setContentType(mediaType);
		responseHeaders.setContentType(new MediaType("text", "json", Charset.forName("UTF-8")));
		ResponseEntity<JSONObject> responseResult = new ResponseEntity<JSONObject>(json, responseHeaders,
				HttpStatus.OK);
		return responseResult;
	}

    @RequestMapping("/updateUser.do")
    //更新个人信息，输入各字段内容
    public void updateUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        //Map<String, Object> map = new HashMap<String, Object>();
        int id;String name,icon,phone,email,password,message,city;

        id = Integer.parseInt(request.getParameter("id"));
        name = request.getParameter("name");
        icon = request.getParameter("icon");
        phone = request.getParameter("phone");
        email = request.getParameter("email");
        password = request.getParameter("password");
        message = request.getParameter("message");
        city = request.getParameter("city");

        //map.put("id",id);map.put("name",name);map.put("icon",icon);map.put("phone",phone);
        //map.put("email",email);map.put("password",password);map.put("message",message);map.put("city",city);
        this.userService.updateUser(id,name,icon,phone,email,password,message,city);

    }
}
